package com.luckdraw.service.impl;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.json.Json;
import org.nutz.log.Log;
import org.nutz.log.Logs;

import com.luckdraw.service.GamePool;
import com.luckdraw.service.GameService;
import com.luckdraw.service.game.Game;

@IocBean(name="gameService")
public class GameServiceImpl implements GameService,GamePool{
	
	private Map<Integer,BlockingQueue<Game>> gamePool = new HashMap<Integer, BlockingQueue<Game>>();
	
	private Map<Integer,Game> games = new HashMap<Integer, Game>();

	private static final Log log = Logs.getLog("GameServiceImpl");
	
	/**
	 * 检查当前游戏是否初始化完成
	 * @param gameId
	 * @return
	 */
	public boolean checkGame(int gameId){
		return games.containsKey(Integer.valueOf(gameId));
	}
	
	public void put(int id,Game game){
		synchronized (gamePool) {
			if(gamePool.containsKey(Integer.valueOf(id))){
				try {
					gamePool.get(Integer.valueOf(id)).offer(game);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}else{
				//生成有一个备用奖池的队列
				BlockingQueue<Game> queue = new LinkedBlockingQueue<Game>(1);
				gamePool.put(Integer.valueOf(id), queue);
				log.info("gamePool.add||gameID:"+id+";gameAwards:"+Json.toJson(game));
			}
		}
	}
	
	public Game poll(int id){
		if(gamePool.containsKey(Integer.valueOf(id))){
			Game game = null;
			try {
				game = gamePool.get(Integer.valueOf(id)).take();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			log.info("gamePool.get||gameID:"+id+";gameAwards:"+Json.toJson(game));
			return game;
		}
		return null;
	}
	
	public int getReward(int id){
		synchronized (games) {
			int reward = 0;
			if(games.containsKey(Integer.valueOf(id))){
				reward = games.get(Integer.valueOf(id)).getReward();
			}
			if(reward==0){
				Game game = poll(id);
				if(game!=null){
					reward = game.getReward();
					games.put(Integer.valueOf(id), game);
				}
			}
			log.info("gamePool.getReward||gameID:"+id+";gameAward:"+reward);
			return reward;
		}
	}
	
}
